package com.zhuhanpeng.cloud.mybatis.flexigrid;

import com.zhuhanpeng.cloud.mybatis.annotation.Column;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * flexigrid插件返回数据实体类
 * @param <T>
 */

public class PadingRstType<T> implements Serializable {
    private Logger logger = LogManager.getLogger(this.getClass());
    /**
     * 总数量
     */
    private Integer total;
    /**
     * 当前页数
     */
    private Integer page;
    /**
     * 每一行的数据
     */
    private List<PageRowsType> rows = new ArrayList<PageRowsType>();
    /**
     * 列头
     */
    private List<Object> columns = new ArrayList<>();
    /**
     * 数据列表
     */
    private List<T> rawRecords;



    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public List<PageRowsType> getRows() {
        return rows;
    }

    public void setRows(List<PageRowsType> rows) {
        this.rows = rows;
    }

    public List<Object> getColumns() {
        return columns;
    }

    public void setColumns(List<Object> columns) {
        this.columns = columns;
    }

    public List<T> getRawRecords() {
        return rawRecords;
    }

    public void setRawRecords(List<T> rawRecords) {
        this.rawRecords = rawRecords;
    }
    public void putItem(){
        if (this.rawRecords == null || rawRecords.size() == 0){
            return;
        }
        Class<?> aClass = this.rawRecords.get(0).getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field:fields){
            if (field.isAnnotationPresent(Column.class)){
                this.columns.add(field.getName());
            }
        }
        PageRowsType pageRowsType = null;
        T item = null;
        Object obj = null;
        for (int i = 0;i< rawRecords.size();i++){
            item = rawRecords.get(i);
            pageRowsType = new PageRowsType();
            this.rows.add(pageRowsType);
            pageRowsType.setId(i);
            for (Field field:fields){
                if (field.isAnnotationPresent(Column.class)){
                    field.setAccessible(true);
                    try {
//
                        obj = field.get(item);
                        pageRowsType.addCell(obj);
                    } catch (IllegalAccessException e) {
//                        e.printStackTrace();
                    }
                }
            }
        }
    }
    public void dealPage(PagingEntity pagingEntity) {
        this.page = pagingEntity.getPage();
        Integer rp = pagingEntity.getRp();
        if((page-1)*rp>total){
            page=1;
            pagingEntity.setPage(page);
        }
    }

}